<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ProtoActor-Go WASM 测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        h1 {
            color: #333;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
        }
        pre {
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 5px;
            overflow: auto;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background-color: #45a049;
        }
        #output {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            min-height: 200px;
        }
        .event-log {
            background-color: #e6f7ff;
            border-left: 3px solid #1890ff;
            padding: 5px 10px;
            margin: 5px 0;
        }
        .error-log {
            background-color: #fff1f0;
            border-left: 3px solid #f5222d;
            padding: 5px 10px;
            margin: 5px 0;
        }
    </style>
</head>
<body>
    <h1>ProtoActor-Go WASM 测试</h1>
    
    <div>
        <button id="init-btn">初始化 WASM</button>
        <button id="create-actor-btn" disabled>创建 Actor</button>
        <button id="send-msg-btn" disabled>发送消息</button>
        <button id="stop-actor-btn" disabled>停止 Actor</button>
        <button id="get-version-btn" disabled>获取版本</button>
        <button id="clear-log-btn">清空日志</button>
    </div>
    
    <h2>输出:</h2>
    <pre id="output">等待初始化...</pre>
    
    <script src="wasm_exec.js"></script>
    <script>
        // 全局变量
        let wasmInstance = null;
        let currentActor = null;
        
        // 事件类型
        const EventType = {
            INITIALIZED: 'initialized',
            ERROR: 'error',
            MESSAGE_RECEIVED: 'messageReceived',
            ACTOR_CREATED: 'actorCreated',
            ACTOR_STOPPED: 'actorStopped',
            MESSAGE_SENT: 'messageSent'
        };
        
        // 事件监听器
        const eventListeners = new Map();
        
        // 添加日志到输出区域
        function log(message, isEvent = false, isError = false) {
            const output = document.getElementById('output');
            
            if (isEvent) {
                const eventDiv = document.createElement('div');
                eventDiv.className = 'event-log';
                eventDiv.textContent = `[事件] ${message}`;
                output.appendChild(eventDiv);
            } else if (isError) {
                const errorDiv = document.createElement('div');
                errorDiv.className = 'error-log';
                errorDiv.textContent = `[错误] ${message}`;
                output.appendChild(errorDiv);
            } else {
                output.appendChild(document.createTextNode(message + '\n'));
            }
            
            // 滚动到底部
            output.scrollTop = output.scrollHeight;
        }
        
        // 清空日志
        function clearLog() {
            document.getElementById('output').innerHTML = '';
        }
        
        // 添加事件监听器
        function addEventListener(eventType, listener) {
            if (!eventListeners.has(eventType)) {
                eventListeners.set(eventType, new Set());
            }
            eventListeners.get(eventType).add(listener);
        }
        
        // 移除事件监听器
        function removeEventListener(eventType, listener) {
            const listeners = eventListeners.get(eventType);
            if (listeners) {
                listeners.delete(listener);
            }
        }
        
        // 触发事件
        function dispatchEvent(eventType, data) {
            const listeners = eventListeners.get(eventType);
            if (listeners) {
                listeners.forEach(listener => {
                    try {
                        listener(data);
                    } catch (error) {
                        console.error(`事件监听器错误 (${eventType}):`, error);
                    }
                });
            }
        }
        
        // 设置事件监听器
        function setupEventListeners() {
            // 初始化完成事件
            addEventListener(EventType.INITIALIZED, () => {
                log('WASM 初始化完成', true);
            });
            
            // 错误事件
            addEventListener(EventType.ERROR, (data) => {
                log(`错误: ${data.error?.message || JSON.stringify(data)}`, false, true);
            });
            
            // 消息接收事件
            addEventListener(EventType.MESSAGE_RECEIVED, (data) => {
                log(`收到消息: ${JSON.stringify(data)}`, true);
            });
            
            // Actor 创建事件
            addEventListener(EventType.ACTOR_CREATED, (data) => {
                log(`Actor 已创建: ${JSON.stringify(data)}`, true);
            });
            
            // Actor 停止事件
            addEventListener(EventType.ACTOR_STOPPED, (data) => {
                log(`Actor 已停止: ${JSON.stringify(data)}`, true);
            });
            
            // 消息发送事件
            addEventListener(EventType.MESSAGE_SENT, (data) => {
                log(`消息已发送: ${JSON.stringify(data)}`, true);
            });
        }
        
        // 调用 Go 函数
        function invokeGoFunction(funcName, argsJson) {
            if (typeof window.invokeGoFunction !== 'function') {
                throw new Error('WASM 模块尚未初始化或未导出 invokeGoFunction');
            }
            return window.invokeGoFunction(funcName, argsJson);
        }
        
        // 初始化 WASM
        async function initWasm() {
            try {
                clearLog();
                log('正在初始化 WASM...');
                
                // 创建 Go 实例
                const go = new Go();
                
                // 设置 TS 桥接对象
                globalThis.__TS_BRIDGE__ = {
                    invokeTS: function(funcName, argsJson) {
                        log(`收到 Go 函数调用: ${funcName}`);
                        
                        if (funcName === 'handleGreeting') {
                            try {
                                const args = JSON.parse(argsJson);
                                const message = args[0];
                                log(`收到消息: ${JSON.stringify(message)}`);
                                
                                // 触发消息接收事件
                                dispatchEvent(EventType.MESSAGE_RECEIVED, { message });
                                
                                // 处理问候消息
                                const response = {
                                    response: `你好，${message.type}!`
                                };
                                
                                return JSON.stringify(response);
                            } catch (e) {
                                log(`错误: ${e.message}`, false, true);
                                dispatchEvent(EventType.ERROR, { error: e });
                                return '';
                            }
                        }
                        
                        return '';
                    }
                };
                
                // 加载 WASM 模块
                const result = await WebAssembly.instantiateStreaming(
                    fetch('protoactor.wasm'),
                    go.importObject
                );
                
                // 启动 WASM 模块
                wasmInstance = result.instance;
                go.run(wasmInstance);
                
                log('WASM 初始化成功!');
                dispatchEvent(EventType.INITIALIZED, null);
                
                // 启用按钮
                document.getElementById('create-actor-btn').disabled = false;
                document.getElementById('get-version-btn').disabled = false;
                
            } catch (error) {
                log(`初始化失败: ${error.message}`, false, true);
                dispatchEvent(EventType.ERROR, { error });
            }
        }
        
        // 创建 Actor
        async function createActor() {
            if (!wasmInstance) {
                log('错误: WASM 尚未初始化', false, true);
                return;
            }
            
            try {
                log('\n创建 Actor...');
                
                const actorName = 'test-actor';
                const argsJson = JSON.stringify([actorName]);
                
                const resultJson = invokeGoFunction('createActor', argsJson);
                const result = JSON.parse(resultJson);
                
                if (result.error) {
                    throw new Error(result.error);
                }
                
                currentActor = result.result;
                log(`Actor 创建成功: ${JSON.stringify(currentActor)}`);
                dispatchEvent(EventType.ACTOR_CREATED, { actorName, pid: currentActor });
                
                // 启用按钮
                document.getElementById('send-msg-btn').disabled = false;
                document.getElementById('stop-actor-btn').disabled = false;
                
            } catch (error) {
                log(`创建 Actor 失败: ${error.message}`, false, true);
                dispatchEvent(EventType.ERROR, { operation: 'createActor', error });
            }
        }
        
        // 发送消息
        async function sendMessage() {
            if (!wasmInstance || !currentActor) {
                log('错误: WASM 尚未初始化或没有可用的 Actor', false, true);
                return;
            }
            
            try {
                log('\n发送消息...');
                
                const message = {
                    type: 'Greeting',
                    content: '你好，Actor!'
                };
                
                dispatchEvent(EventType.MESSAGE_SENT, { pid: currentActor, message });
                
                const argsJson = JSON.stringify([currentActor, message]);
                
                const resultJson = invokeGoFunction('sendMessage', argsJson);
                const result = JSON.parse(resultJson);
                
                if (result.error) {
                    throw new Error(result.error);
                }
                
                log(`消息发送成功，响应: ${JSON.stringify(result.result)}`);
                
            } catch (error) {
                log(`发送消息失败: ${error.message}`, false, true);
                dispatchEvent(EventType.ERROR, { operation: 'sendMessage', error });
            }
        }
        
        // 停止 Actor
        async function stopActor() {
            if (!wasmInstance || !currentActor) {
                log('错误: WASM 尚未初始化或没有可用的 Actor', false, true);
                return;
            }
            
            try {
                log('\n停止 Actor...');
                
                const argsJson = JSON.stringify([currentActor]);
                
                const resultJson = invokeGoFunction('stopActor', argsJson);
                const result = JSON.parse(resultJson);
                
                if (result.error) {
                    throw new Error(result.error);
                }
                
                log(`Actor 已停止: ${JSON.stringify(result.result)}`);
                dispatchEvent(EventType.ACTOR_STOPPED, { pid: currentActor, result: result.result });
                
                // 禁用按钮
                document.getElementById('send-msg-btn').disabled = true;
                document.getElementById('stop-actor-btn').disabled = true;
                currentActor = null;
                
            } catch (error) {
                log(`停止 Actor 失败: ${error.message}`, false, true);
                dispatchEvent(EventType.ERROR, { operation: 'stopActor', error });
            }
        }
        
        // 获取版本
        async function getVersion() {
            if (!wasmInstance) {
                log('错误: WASM 尚未初始化', false, true);
                return;
            }
            
            try {
                log('\n获取版本信息...');
                
                const resultJson = invokeGoFunction('getVersion', '[]');
                const result = JSON.parse(resultJson);
                
                if (result.error) {
                    throw new Error(result.error);
                }
                
                log(`版本信息: ${result.result}`);
                
            } catch (error) {
                log(`获取版本失败: ${error.message}`, false, true);
                dispatchEvent(EventType.ERROR, { operation: 'getVersion', error });
            }
        }
        
        // 初始化页面
        function initPage() {
            // 设置事件监听器
            setupEventListeners();
            
            // 绑定按钮事件
            document.getElementById('init-btn').addEventListener('click', initWasm);
            document.getElementById('create-actor-btn').addEventListener('click', createActor);
            document.getElementById('send-msg-btn').addEventListener('click', sendMessage);
            document.getElementById('stop-actor-btn').addEventListener('click', stopActor);
            document.getElementById('get-version-btn').addEventListener('click', getVersion);
            document.getElementById('clear-log-btn').addEventListener('click', clearLog);
        }
        
        // 页面加载完成后初始化
        window.addEventListener('load', initPage);
    </script>
</body>
</html> 
</html> 